package com.aitaoxue.palx.fragment;

import java.lang.ref.WeakReference;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;

import com.aitaoxue.palx.R;
import com.aitaoxue.palx.db.SearchHistory.HistoryEntry;
import com.aitaoxue.palx.db.SearchHistoryDBHelper;
import com.aitaoxue.palx.widget.ClearEditText;

public class SearchHistoryFragment extends Fragment implements
		OnItemClickListener {

	@InjectView(R.id.lv_search_history)
	ListView listview;

	private SearchHistoryDBHelper dbHelper;
	private SQLiteDatabase db;

	private AsyncTask<Void, Void, Cursor> task;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_search_history, null);
		ButterKnife.inject(this, view);

		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);

		task = new HistoryTask(getActivity()).execute();
	}

	private class HistoryTask extends AsyncTask<Void, Void, Cursor> {

		private WeakReference<Context> mContext;

		private HistoryTask(Context context) {
			mContext = new WeakReference<Context>(context);
		}

		@Override
		protected Cursor doInBackground(Void... arg0) {
			dbHelper = new SearchHistoryDBHelper(mContext.get());
			try {
				db = dbHelper.getReadableDatabase();
			} catch (Exception e) {
				e.printStackTrace();
			}

			Cursor cursor = db.rawQuery("select distinct * from "
					+ HistoryEntry.TABLE_NAME + " order by "
					+ HistoryEntry.COLUMN_TIME + " desc", null);

			return cursor;
		}

		@Override
		protected void onPostExecute(Cursor result) {
			if (result != null) {
				notifyGetHistory(result);
			}
		}
	}

	private void notifyGetHistory(Cursor cursor) {
		@SuppressWarnings("deprecation")
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(getActivity(),
				R.layout.search_history_item, cursor,
				new String[] { HistoryEntry.COLUMN_CONTENT },
				new int[] { R.id.tv_search_history });

		listview.setAdapter(adapter);
		listview.setOnItemClickListener(this);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int position,
			long arg3) {
		TextView tv=(TextView) view.findViewById(R.id.tv_search_history);
		String text=tv.getText().toString();
		
		//获得关键词
		ClearEditText ce=(ClearEditText) getActivity().findViewById(R.id.search_content);
		ce.setText(text);
	}

}
